package chen.web.forum;

import chen.web.user.Account;

public class ReplyCondition {
	
	public static enum Order{
		/**
		 * 按发表时间正序排列
		 */
		Asc, 
		/**
		 * 按发表时间倒序排列
		 */
		Desc
	}
	
	private ForumAccount account;
	private Subject subject;
	private boolean fakeDelete;
	private boolean needChecking;
	private Order order = Order.Asc;
	private Category category;
	private boolean containsChildren = false;
	
	public ReplyCondition setAccount(ForumAccount account) {
		this.account = account;
		return this;
	}
	public ForumAccount getAccount() {
		return account;
	}
	public ReplyCondition setSubject(Subject subject) {
		this.subject = subject;
		return this;
	}
	public Subject getSubject() {
		return subject;
	}
	public ReplyCondition setFakeDelete(boolean fakeDelete) {
		this.fakeDelete = fakeDelete;
		return this;
	}
	public boolean isFakeDelete() {
		return fakeDelete;
	}
	public ReplyCondition setNeedChecking(boolean needChecking) {
		this.needChecking = needChecking;
		return this;
	}
	public boolean isNeedChecking() {
		return needChecking;
	}
	public ReplyCondition setOrder(Order order) {
		this.order = order;
		return this;
	}
	public Order getOrder() {
		return order;
	}
	
	public String toSql(){
		String and = " and ";
		StringBuffer sql = new StringBuffer();
		if(getAccount() != null){
			sql.append("reply_authorId = ").append(getAccount().getId()).append(' ');
			sql.append(and);
		}
		if(getSubject() != null){
			sql.append("sub_id = ").append(getSubject().getId()).append(' ');
			sql.append(and);
		}
		if(isNeedChecking()){ 		//需要审核的
			sql.append("reply_invisible = 2 ").append(and);
		} else if(isFakeDelete()){	//假删除的
			sql.append("reply_invisible = 1 ").append(and);
		} else {					//可见的
			sql.append("reply_invisible = 0 ").append(and);
		}
		
		//多表查询
		if(getCategory() != null){
			String cids = SubjectCondition.getCategoryIdStr(getCategory(), isContainsChildren());
			if(cids.length() != 0){
				sql.append("cat_id in(");
				sql.append(cids);
				sql.append(")");
				sql.append(and);	
			}
			//多表查询
			sql.append("web_subject.sub_id = web_subject_reply.sub_id").append(and);
		}
		
		if(sql.length() > 0){
			sql.delete(sql.length()-and.length(), sql.length());	
			sql.insert(0, " where ");
		}
		
		if(getOrder() != null){
			sql.append(" order by reply_dateline ")
			.append(getOrder().name())
			.append(" ");	
		}
		return sql.toString();
	}
	public ReplyCondition setCategory(Category category) {
		//只设置非根目录
		if(category.getId() != CategoryManager.RootCategoryId){
			this.category = category;	
		}
		return this;
	}
	public Category getCategory() {
		return category;
	}
	public ReplyCondition setContainsChildren(boolean containsChildren) {
		this.containsChildren = containsChildren;
		return this;
	}
	public boolean isContainsChildren() {
		return containsChildren;
	}
}
